package fmt_e

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2021-06-15
Description: 根据枚举结构自动生成对应成员的fmt.IStringer接口
*******************************************************************************/
import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strings"
)

func FmtFileEnumStringer(params []string) error {
	if len(params) < 1 {
		return fmt.Errorf("No file path specified")
	}

	file_path := params[0]

	enum_name, parsed, isCase := "", false, false
	if len(params) > 1 {
		enum_name = params[1]
	}
	if len(params) > 2 {
		for _, v := range params[2:] {
			if v == "-p" {
				parsed = true
			} else if v == "-c" {
				isCase = true
			}
		}
	}

	f, err := os.Open("./" + file_path)
	if err != nil {
		return err
	}

	var fmted_buf bytes.Buffer

	unit, fmted, buf := (*EnumUnit)(nil), false, bufio.NewReader(f)
	for {
		line, err := buf.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				line += "\n"
				fmted_buf.WriteString(line)
				break
			}
			return err
		}

		line_ := strings.TrimSpace(line)
		if strings.HasPrefix(line_, "type ") {
			unit = nil // 重置
		}

		if strings.HasPrefix(line_, "type E") && (strings.Contains(line_, "int32") || strings.Contains(line_, "int")) {
			ename := strings.Fields(line_)[1]
			if enum_name == "" || enum_name == ename {
				unit = &EnumUnit{name: ename}
				fmted_buf.WriteString(line)
				continue
			}
		}

		if unit != nil {
			switch {
			// 开始添加成员
			case !unit.adding && strings.Contains(line_, unit.name) && !strings.Contains(line_, "func"):
				unit.adding = true
				unit.addMember(strings.Fields(line_)[0])
			// 结束添加成员
			case unit.adding && strings.HasPrefix(line_, ")"):
				unit.adding = false // 这个地方要处理增加修改量了
				fmted_buf.WriteString(line)
				fmted = true
				fmted_buf.WriteString(unit.fmtstr(isCase))
				if parsed {
					fmted_buf.WriteString(unit.parstr())
				}
				fmted_buf.WriteString(unit.vrfstr())
				continue
			// 继续添加
			case unit.adding:
				if len(line_) > 0 {
					unit.addMember(strings.Fields(line_)[0])
				}

			// 过滤已存在的
			case !unit.infun && strings.Contains(line_, unit.name) && strings.Contains(line_, "String()"):
				unit.infun = true
				continue
			case !unit.infun && strings.Contains(line_, unit.name) && strings.Contains(line_, "Verify()"):
				unit.infun = true
				continue
			case !unit.infun && strings.Contains(line_, unit.name) && strings.Contains(line_, "Parse(s string)"):
				unit.infun = true
				continue
			case unit.infun && strings.HasPrefix(line, "}"):
				unit.infun = false
				continue
			case unit.infun:
				continue
			}
		}

		fmted_buf.WriteString(line)
	}
	f.Close()

	if !fmted {
		return fmt.Errorf("nothing")
	}
	// 写调整后的
	f, err = os.OpenFile("./"+file_path, os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		return err
	}
	fmted_buf.WriteTo(f)
	f.Close()

	return nil
}
